<?php


/*
 * File authentication.php for project Rijlesplanner.nl
 * Created on 25 nov 2007 at 16:22:11 by Ivar Pruijn
 */
class authentication extends modules {

	// Properties:
	protected $name = "authentication";
	protected $title = "Authenticatie";
	protected $subtitle = "";
	protected $moduleOptions = array ();
	private $authenticationManager;

	// Methods:

	/**
	 * void __construct ()
	 * This is the constructor method for this class.
	 */
	public function __construct() {
		parent :: __construct();
		$this->logger = parent :: getLogger();
		$this->user = parent :: getUser();
		$this->template = parent :: getTemplate();
		$this->wsclient = parent :: getWsclient();
		$this->auth = parent :: getAuth();
	}

	/**
	 * Object process()
	 * 
	 * Processes the template and current module
	 * 
	 * @param Smarty template The Smarty template to process (sets variables etc.)
	 * @return Smarty The template that has been processed
	 */
	function process(& $template = null) {
		$this->template = $template;
		if (!empty ($_POST)) {
			switch ($_POST['action']) {
				case "login" :
					if ($this->auth->accessTo($this->name)) {
						$loggedIn = $this->login();
						$this->template->assign('loggedIn', $loggedIn);
						$this->template->assign('loginAction', true);
					} else {
						$this->actionAccessDenied();
					}
					$this->template->assign('moduleTemplate', 'modules/authentication/login.tpl');
					break;
				case "logout" :
					$this->logout();
					$this->template->assign('moduleTemplate', 'modules/authentication/logout.tpl');
					break;
			}
		} else {
			$this->template->assign('moduleTemplate', 'modules/authentication/login.tpl');
		}
	}

	/**
	 * boolean login()
	 * 
	 * Login functionality
	 * Sets an error array in the template in case of errors.
	 * 
	 * @return boolean whether the login was sucessful
	 */
	function login() {
		$loginresult = 0;
		$errors = array ();
		try {
			if (!isset ($_POST['rijschool']) || empty ($_POST['rijschool'])) {
				throw new AuthenticationException('De rijschoolcode is niet ingevuld', 2);
			}
			if (!isset ($_POST['email']) || empty ($_POST['email'])) {
				throw new AuthenticationException('Het emailadres is niet ingevuld', 3);
			}
			if (!isset ($_POST['password']) || empty ($_POST['password'])) {
				throw new AuthenticationException('Het wachtwoord is niet ingevuld', 4);
			}
			$rijschool = $this->wsclient->WS_Rijschool_Info(array (
				'Handle' => $_POST['rijschool']
			));
            
            if ($rijschool->Beta) {
                echo "<script>";
                echo "top.location='http://beta.rijlesplanner.nl/" . $_POST['rijschool'] . "';";
                echo "</script>";
                exit;                
            }
            
			$result = $this->wsclient->WS_Rijschool_Login_Leerling(array (
				'RijschoolId' => $rijschool->Id,
				'Username' => $_POST['email'],
				'Password' => $_POST['password']
			));
			
			if (isset ($result->SessionId) && !empty ($result->SessionId)) {
				$this->logger->log("User logged in with Session ID:" . $result->SessionId . "!", PEAR_LOG_DEBUG);
				//session_id($result->SessionId);
				$_SESSION['SessionId'] = $result->SessionId;
				$user = $result->Leerling;
				$user->setRijschoolId($rijschool->Id);
				$user->setRijschoolNaam($rijschool->Naam);
				$user->setAdvertenties($rijschool->Advertenties);
				$afbeelding = $user->getAfbeelding();
				if(empty($afbeelding)) {
					// default empty image
					$user->setAfbeelding('/images/' . $_SESSION['LayoutStyle'] . '/' . $this->config['default_leerling_photo']);
				}
				$dashboardAcl = $result->ACL;
				$acl = array (
					"authentication" => array (),
					"content" => array (
						"options" => array (
							"overrijlesplanner",
							"sitemap"
						),
						"actions" => array ()
					),
					"rijschool" => array (
						"options" => array (
							"mededelingen"
						),
						"actions" => array()
					),
					"financieel" => array (),
					"home" => array (
						"options" => array (
							"eigenverklaring",
							"algemenevoorwaarden",
							"algemenevoorwaardendownloaden",
						),
						"actions" => array(
							"akkoordeigenverklaring",
							"akkoordalgemenevoorwaarden"
						)
					),
					"persoonlijk" => array (
						"options" => array (
							"gegevens"
						),
						"actions" => array(
							"wijzigfoto"
						)
					),
					"praktijk" => array (
						"options" => array (),
						"actions" => array ()
					),
					"reviews" => array (
						"options" => array (
							#	"berichten",
							# "plaatsreactie",
							# "vindreacties"
						),
						"actions" => array (
							# "plaatsreactie",
							# "vindreactie"
						)
					),
					"statistics" => array (),
					"tellafriend" => array (
						"options" => array(
							"tellafriend"
						),
						"actions" => array(
							"sendtellafriend" 
						)
					),
					"theorie" => array (
						"options" => array (
							"theorierijschool",
							"theorieplannen",
							"theorieleren",
							"theorieexamens"
						),
						"actions" => array (
							"selectCursus",
							"plannen",
							"annuleren",
							"theoriedetails",
							"theorieaanvragen"
						)
					),
					"blog" => array (
						"options" => array(),
						"actions" => array()
					),
					"ads" => array (
						"options" => array(),
						"actions" => array()
					)
				);
				// Process Dashboard ACL: AGENDA_VIEW, AGENDA_EDIT, TRANSACTIES_VIEW, VORDERINGEN_VIEW, LEERLING_EDIT
				$agendaOptionsACL = $acl["praktijk"]["options"];
				$agendaActionsACL = $acl["praktijk"]["actions"];
				$persoonlijkOptionsACL = $acl["persoonlijk"]["options"];
				$persoonlijkActionsACL = $acl["persoonlijk"]["actions"];
				$reviewsOptionsACL = $acl["reviews"]["options"];
				$reviewsActionsACL = $acl["reviews"]["actions"];
				if(in_array("AGENDA_VIEW",$dashboardAcl)) {
					$agendaOptionsACL[] = "cursusoverzicht";
					$acl["praktijk"]["options"]  = $agendaOptionsACL;
					$agendaActionsACL[] = "cursusoverzicht";
					$acl["praktijk"]["actions"]  = $agendaActionsACL;
				}
				if(in_array("AGENDA_EDIT",$dashboardAcl)) {
					$agendaOptionsACL[] = "lessenplannen";
					$acl["praktijk"]["options"]  = $agendaOptionsACL;
					$agendaActionsACL[] = "lessenplannenblok";
					$agendaActionsACL[] = "praktijkplannen";
					$agendaActionsACL[] = "praktijkannuleren";
					$acl["praktijk"]["actions"]  = $agendaActionsACL;
				}
				if(in_array("TRANSACTIES_VIEW",$dashboardAcl)) {
					$persoonlijkOptionsACL[] = "financieel";
					$acl["persoonlijk"]["options"]  = $persoonlijkOptionsACL;
				}
				if(in_array("LEERLING_EDIT",$dashboardAcl)) {
					$persoonlijkOptionsACL[] = "fotowijzigen";
					$acl["persoonlijk"]["options"]  = $persoonlijkOptionsACL;
					$persoonlijkActionsACL[] = "wijziggegevens";
					$persoonlijkActionsACL[] = "fotowijzigen";
					$acl["persoonlijk"]["actions"]  = $persoonlijkActionsACL;
				}
				if(in_array("VORDERINGEN_VIEW",$dashboardAcl)) {
					$acl["praktijk"]["options"][] = "vorderingskaarten";
					$acl["praktijk"]["actions"][] = "vorderingskaarten";
				}
				
				# Feature: 000136
				if(in_array("BERICHTEN_BEKIJKEN",$dashboardAcl)) {
					$reviewsOptionsACL[] = "berichten";
					$reviewsOptionsACL[] = "vindreacties";
					$acl["reviews"]["options"] = $reviewsOptionsACL;
					$reviewsActionsACL[] = "vindreactie";
					$acl["reviews"]["actions"] = $reviewsActionsACL;
				}
				if(in_array("BERICHTEN_PLAATSEN",$dashboardAcl)) {
					$reviewsOptionsACL[] = "plaatsreactie";
					$acl["reviews"]["options"] = $reviewsOptionsACL;
					$reviewsActionsACL[] = "plaatsreactie";
					$acl["reviews"]["actions"] = $reviewsActionsACL;
				}
				$user->setAcl($acl);
				$this->logger->log($acl);
				$_SESSION['LayoutStyle'] = $result->LayoutStyle;
				$_SESSION['Plantijd'] = $result->Plantijd;
				$_SESSION['Annuleertijd'] = $result->Annuleertijd;
        $_SESSION['Plantermijn'] = $result->Plantermijn;
				$_SESSION['MaxPerWeek'] = $result->MaxPerWeek;
													
				$_SESSION['user'] = $user;
				$this->user = $user;
				
				$_SESSION['NietAkkoord'] = $result->NietAkkoord;
				$loginresult = 1;
				$this->setSubtitle("Ingelogd");
				
			} else {
				throw new AuthenticationException('E-mailadres of wachtwoord niet correct', 6);
			}
		} catch (SoapFault $e) {
			$this->logger->log("SOAP Fault: (faultcode: {$e->faultcode} faultstring: {$e->faultstring})", PEAR_LOG_DEBUG);
			switch ($e->faultcode) {
				case 1 :
					$errorcode = 1;
					$errormessage = 'De rijschoolcode is niet bekend';
					break;
				default :
					$errorcode = 5;
					$errormessage = 'Een onbekende fout is opgetreden bij inloggen';
					break;
			}
			$errors[] = array (
				'code' => $errorcode,
				'message' => $errormessage
			);
			$this->setSubtitle($errormessage);
		} catch (AuthenticationException $e) {
			$errors[] = array (
				'code' => $e->getCode(),
				'message' => $e->getMessage()
			);
			$this->setSubtitle($e->getMessage());
		}

		$this->template->assign('errors', $errors);
		return $loginresult;
	}

	/**
	 * boolean logout()
	 * 
	 * Logout functionality. 
	 * Sets an error array in the template in case of errors.
	 * 
	 * @return boolean whether the logout was sucessful
	 */
	private function logout() {
		$logoutresult = 0;
		$errors = array ();
		$this->loggedIn = false;

		
		$this->auth->setUser(new Visitor());
		$referer = $this->auth->determineReferer("");
		$this->template->assign('referer',$this->config['siteurl']);
		$_SESSION['layoutstyle'] = 'default';
				


		if ($this->user instanceof Leerling) {
			try {
				$result = $this->wsclient->WS_Rijschool_Logout(array (
					'RijschoolId' => $this->user->getRijschoolId(),
					'SessionId' => $_SESSION['SessionId']
				));
				if (isset ($result->Success) && $result->Success == 1) {
					$logoutresult = $this->kill_session();
				} else {
					throw new AuthenticationException('Onbekende fout bij uitloggen', 7);
					exit;
				}
			} catch (SoapFault $e) {
				$this->logger->log("SOAP Fault: (faultcode: {$e->faultcode} faultstring: {$e->faultstring})", PEAR_LOG_DEBUG);
				switch ($e->faultcode) {
					default :
						$errorcode = 8;
						$errormessage = 'Een onbekende fout is opgetreden bij uitloggen: ' . $e->faultstring;
						break;
				}
				$errors[] = array (
					'code' => $errorcode,
					'message' => $errormessage
				);
				$this->setSubtitle($errormessage);
			} catch (AuthenticationException $e) {
				$errors[] = array (
					'code' => $e->getCode(),
					'message' => $e->getMessage()
				);
				$this->setSubtitle($e->getMessage());
			}
		} else {
			$logoutresult = $this->kill_session();
		}
		if ($logoutresult) {
			$this->setSubtitle("Uitgelogd");
		}

		$this->template->assign('errors', $errors);
		return $logoutresult;
	}

	/**
	 * Kill the current session
	 */
	function kill_session() {
		$session_id = isset ($_SESSION['SessionId']) ? $_SESSION['SessionId'] : session_id();
		$logoutresult = 1;
		$this->template->assign('loggedIn', 0);
		if (isset ($_COOKIE[session_name()])) {
			@ setcookie(session_name(), '', time() - 42000, '/');
		}
		session_unset();
		session_destroy();
		$_SESSION = array ();
		$this->logger->log("User " . $this->user . " logged out with Session ID:" . $session_id . "!", PEAR_LOG_DEBUG);
		return 1;
	}

	public function getTitle() {
		return $this->title;
	}

	public function getSubTitle() {
		if (!empty ($_GET['option'])) {
			$subtitle = "";
			foreach ($this->moduleOptions AS $mOpt) {
				if ($mOpt['name'] == $_GET['option']) {
					$subtitle = $mOpt['title'];
				}
			}
			return $subtitle;
		} else {
			return $this->subtitle;
		}
	}

	public function setSubTitle($newVal = "") {
		if (!empty ($newVal)) {
			$this->subtitle = $newVal;
		}
	}

	/*
	 * string __toString()
	 * 
	 * Returns a String representation of this class.
	 * 
	 * @return string A representation of this class
	 */
	public function __toString() {
		return $this->title;
	}
}
?>